const express = require("express");
const app = express();
const fs = require("fs");
const path = require("path");
const { getDb, saveDb } = require("./db");

// 配置解析表单请求体：application/json
app.use(express.json());
// 解析表单请求体：application/x-www-form-urlencoded
app.use(express.urlencoded());

app.get("/todos", async (req, res) => {
  try {
    const data = await getDb();
    res.status(200).json({
      todos: data.todos,
    });
  } catch (err) {
    res.status(500).json({
      error: err.message,
    });
  }
});

app.get("/todos/:id", async (req, res) => {
  try {
    const { id } = req.params;
    const data = await getDb();
    const todos = data.todos;
    const todo = todos.find((o) => o.id === +id);
    if (!todo) {
      return res.status(404).end();
    }
    res.status(200).json({
      todo: todo,
    });
  } catch (error) {
    res.status(500).json({
      error: error.message,
    });
  }
});

app.post("/todos", async (req, res) => {
  try {
    const db = await getDb();
    const { todo } = req.body;
    if (!todo.title) {
      return res.status(422).json({
        error: "title字段必传",
      });
    }

    let lastTodo = db.todos[db.todos.length - 1];
    todo.id = lastTodo ? lastTodo.id + 1 : 1;
    db.todos.push(todo);
    await saveDb(db);
    res.status(200).json({
      todos: todo,
      message: "新增成功",
    });
  } catch (error) {
    res.status(500).json({
      error: error.message,
    });
  }
});

app.patch("/todos/:id", async (req, res) => {
  try {
    const { id } = req.params;
    const todo = req.body;
    const db = await getDb();
    const ret = db.todos.find((todo) => todo.id === +id);
    if (!ret) {
      return res.status(404).json();
    }

    Object.assign(ret, todo);
    await saveDb(db);
    res.status(200).json(ret);
  } catch (error) {
    res.status(500).json({
      error: error.message,
    });
  }
});

app.delete("/todos/:id?", async (req, res) => {
  try {
    const { id } = req.params;
    if (!id) {
      return res.status(422).json({
        error: "id必传",
      });
    }

    const db = await getDb();
    const index = db.todos.findIndex((todo) => todo.id === +id);
    if (index === -1) {
      return res.status(404).json({
        message: "暂无数据",
      });
    }

    db.todos.splice(index, 1);
    await saveDb(db);
    res.status(204).json({
      message: "删除成功",
    });
  } catch (error) {
    res.status(500).json({
      error: error.message,
    });
  }
});

app.listen(3000, () => {
  console.log("server is running at http://localhost:3000");
});
